class Solution:
    def findAnagrams(self, s: str, p: str) -> List[int]:
        t = p
        
        need = collections.defaultdict(int)
        window = collections.defaultdict(int)
        
        for char in t:
             need[char] += 1
            
        res = []
        left, right = 0, 0
        valid = 0
        start = 0
        min_len = float('inf')
        
        while right < len(s):
            c = s[right]
            
            if c in need:
                window[c] += 1
                if window[c] == need[c]:
                    valid += 1
            
            right += 1
        
            while right - left == len(t):
                # 缩小窗口的时机：窗口中的字符串长度==目标字符串长度
                if len(need) == valid:
                    # 更新结果的时机：窗口中的字符串长度 == 有效字符串长度
                    res.append(left)
                                    
                d = s[left]
                
                if d in need:
                    if window[d] == need[d]:
                        valid -= 1
                    window[d] -= 1
                
                left += 1
        return res